//
//  BluetoothViewController.m
//  Anyair
//
//  Created by karlcool on 14-5-18.
//  Copyright (c) 2014年 Karlcool. All rights reserved.
//

#import "BluetoothViewController.h"



@interface BluetoothViewController ()

@end

@implementation BluetoothViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    if ([BluetoothManager createManager].senor.manager.state == CBCentralManagerStatePoweredOff) {
        
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"无法扫描设备" message:@"请在设置中打开蓝牙" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
        [alert show];
        [self clickLeft:nil];
        
    } else {
        sensor = [BluetoothManager createManager].senor;//使用全局sensor,以便于管理
        sensor.delegate = self;
        self.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4];
        
        
        UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(35, 100, 250, 240)];
        backView.backgroundColor = [UIColor whiteColor];
        backView.layer.cornerRadius = 5;
        [self.view addSubview:backView];
        
        UILabel *headLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 250, 50)];
        headLabel.backgroundColor = [UIColor clearColor];
        headLabel.textAlignment = 1;
        headLabel.text = @"请选择要连接的设备";
        [backView addSubview:headLabel];
        
        UIView *breakLineView = [[UIView alloc]initWithFrame:CGRectMake(0, 49, 250, 0.5)];
        breakLineView.backgroundColor = BREAKLINE_GRAY;
        [backView addSubview:breakLineView];
        
        blueTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 50, 250, 150) style:UITableViewStylePlain];
        blueTableView.layer.cornerRadius = 5;
        blueTableView.dataSource = self;
        blueTableView.delegate = self;
        blueTableView.separatorInset = UIEdgeInsetsZero;
        blueArray = [[NSMutableArray alloc]init];
        
        [backView addSubview:blueTableView];
        if ([BluetoothManager createManager].isConnected&&[BluetoothManager createManager].senor.activePeripheral.name!=nil) {
            conTextView = [[UITextView alloc]initWithFrame:CGRectMake(0, 70, 250, 150)];
            conTextView.userInteractionEnabled = NO;
            conTextView.selectable = NO;
            conTextView.font = [UIFont systemFontOfSize:17];
            conTextView.textAlignment = 1;
            conTextView.backgroundColor = [UIColor whiteColor];
            conTextView.text = [NSString stringWithFormat:@"已连接到%@,您可以选择重新连接",[BluetoothManager createManager].senor.activePeripheral.name];
            [backView addSubview:conTextView];
            [backView bringSubviewToFront:conTextView];
            
        }
        UIButton *cancelBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 200, 125, 40)];
        [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        [cancelBtn setTitleColor:AIR_GREEN forState:UIControlStateNormal];
        [cancelBtn setTitleColor:AIR_GREEN_DEEP forState:UIControlStateHighlighted];
        [cancelBtn addTarget:self action:@selector(clickLeft:) forControlEvents:UIControlEventTouchUpInside];
        [backView addSubview:cancelBtn];
        
        scanBtn = [[UIButton alloc]initWithFrame:CGRectMake(125.5, 200, 125, 40)];
        if ([BluetoothManager createManager].isConnected) {
            [scanBtn setTitle:@"重连" forState:UIControlStateNormal];
        } else {
            //未连接时刚加载先扫描一次
            [self clickRight:nil];
            [scanBtn setTitle:@"扫描" forState:UIControlStateNormal];
        }
        [scanBtn setTitleColor:AIR_GREEN forState:UIControlStateNormal];
        [scanBtn setTitleColor:AIR_GREEN_DEEP forState:UIControlStateHighlighted];
        [scanBtn addTarget:self action:@selector(clickRight:) forControlEvents:UIControlEventTouchUpInside];
        [backView addSubview:scanBtn];
        
        UIView *breakLineView1 = [[UIView alloc]initWithFrame:CGRectMake(0, 199, 250, 0.5)];
        breakLineView1.backgroundColor = BREAKLINE_GRAY;
        [backView addSubview:breakLineView1];
        
        UIView *breakLineView2 = [[UIView alloc]initWithFrame:CGRectMake(124.5, 199, 0.5, 40)];
        breakLineView2.backgroundColor = BREAKLINE_GRAY;
        [backView addSubview:breakLineView2];
    }
    
    
    
    
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return blueArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    BluetoothCell *cell = (BluetoothCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"BluetoothCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    
    cell.textLabel.text = ((CBPeripheral*)blueArray[indexPath.row]).name;
    cell.pUUID = ((CBPeripheral*)blueArray[indexPath.row]).identifier.UUIDString;
    cell.textLabel.textColor = [UIColor lightGrayColor];
    cell.delegate = self;
    [cell enableInfo];
    cell.connectState.textColor = AIR_GREEN;
    cell.connectState.alpha = 0;
    
    NSString *connectName = [[NSUserDefaults standardUserDefaults]objectForKey:@"connectedUUID"];
    
    if ([cell.textLabel.text isEqualToString:connectName]) {
        cell.connectState.alpha = 1;
    }
    
    return cell;
}

#pragma mark - 查看蓝牙设备信息

- (void)clickInfoBtn:(UIButton*)btn InCell:(BluetoothCell*)myCell {
    
    UIView *InfoView = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    InfoView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3];
    InfoView.userInteractionEnabled = YES;
    InfoView.alpha = 0;
    [self.view addSubview:InfoView];
    
    UIView *InfoBackView = [[UIView alloc]initWithFrame:CGRectMake(-0.5, 200, 321, 100)];
    InfoBackView.backgroundColor = [UIColor whiteColor];
    InfoBackView.layer.borderColor = BREAKLINE_GRAY.CGColor;
    InfoBackView.layer.borderWidth = 0.5;
    [InfoView addSubview:InfoBackView];
    
    UILabel *nameText = [[UILabel alloc]initWithFrame:CGRectMake(20, 10, 300, 30)];
    nameText.backgroundColor = [UIColor clearColor];
    nameText.text = myCell.textLabel.text;
    nameText.textAlignment = NSTextAlignmentLeft;
    [InfoBackView addSubview:nameText];
    
    UILabel *UUIDText = [[UILabel alloc]initWithFrame:CGRectMake(20, 60, 300, 30)];
    UUIDText.backgroundColor = [UIColor clearColor];
    UUIDText.font = [UIFont systemFontOfSize:12];
    UUIDText.text = myCell.pUUID;
    UUIDText.textAlignment = NSTextAlignmentLeft;
    [InfoBackView addSubview:UUIDText];
    
    [UIView animateWithDuration:0.3 animations:^{
        InfoView.alpha = 1;
    }];

    UITapGestureRecognizer *dismissTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dismissInfo:)];
    [InfoView addGestureRecognizer:dismissTap];
    
}

- (void)dismissInfo:(UITapGestureRecognizer*)recognizer {
    
    [UIView animateWithDuration:0.3 animations:^{
        recognizer.view.alpha = 0;
    } completion:^(BOOL finished) {
        [recognizer.view removeFromSuperview];
        [recognizer.view removeGestureRecognizer:recognizer];
    }];
    
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSString *connectedUUID = [[NSUserDefaults standardUserDefaults]objectForKey:@"connectedUUID"];//从用户配置中取出当前连接的设备UUID
    CBPeripheral *p = blueArray[indexPath.row];
    NSString *currentUUID = p.identifier.UUIDString;
    
    //如果原本连接有设备就先断开
    if (sensor.activePeripheral!=nil) {
        if ([currentUUID isEqualToString:connectedUUID]) {
            
        } else {
            [sensor disconnect:sensor.activePeripheral];
            [[NSUserDefaults standardUserDefaults]setObject:currentUUID forKey:@"connectedUUID"];
            [sensor connect:p];
        }
        
    } else {
        [[NSUserDefaults standardUserDefaults]setObject:currentUUID forKey:@"connectedUUID"];
        [sensor connect:p];
    }

    [sensor stopScan];
    
    //设置选中态
    NSArray *cellArray = [tableView visibleCells];
    for (BluetoothCell *tempCell in cellArray) {
        if ([tempCell.textLabel.text isEqualToString:p.name]) {
            
            [UIView animateWithDuration:0.3 animations:^{
                tempCell.connectState.alpha = 1;
            }];
        }
    }
}

#pragma mark - 顶栏委托

#pragma mark - 退出蓝牙列表
- (void)clickLeft:(UIButton*)sender {
    [UIView animateWithDuration:0.2 animations:^{
        self.view.alpha = 0;
    } completion:^(BOOL finished) {
        [self.view removeFromSuperview];
        [self removeFromParentViewController];
    }];
}

#pragma mark - 扫描蓝牙设备
- (void)clickRight:(UIButton*)sender {

    if ([sensor activePeripheral]) {
        if (sensor.activePeripheral.state == CBPeripheralStateConnected) {
            [sensor.manager cancelPeripheralConnection:sensor.activePeripheral];
            sensor.activePeripheral = nil;
        }
    }
    if ([sensor peripherals]) {
        sensor.peripherals = nil;
        [blueArray removeAllObjects];
        [blueTableView reloadData];
    }
    blueTableView.alpha = 1;
    [conTextView removeFromSuperview];
    printf("开始扫描设备");
    [sender setTitle:@"扫描中" forState:UIControlStateNormal];
    scanTimer = [NSTimer scheduledTimerWithTimeInterval:SCAN_TIME target:self selector:@selector(timeOut) userInfo:nil repeats:NO];
    [sensor findHMSoftPeripherals:SCAN_TIME];
    
}

- (void)timeOut {
    [scanBtn setTitle:@"扫描" forState:UIControlStateNormal];
}

#pragma mark - 蓝牙委托
-(void)sensorReady {

}

- (void) setConnect {
    [BluetoothManager createManager].isConnected = YES;
    [self clickLeft:nil];
    MBProgressHUD *shortHub = [[MBProgressHUD alloc]initWithView:[UIApplication sharedApplication].keyWindow];
    [[UIApplication sharedApplication].keyWindow addSubview:shortHub];
    [shortHub setLabelText:[NSString stringWithFormat:@"已连接到%@",[BluetoothManager createManager].senor.activePeripheral.name]];
    [shortHub setMode:MBProgressHUDModeText];
    [shortHub hide:YES afterDelay:1.5];
    [shortHub show:YES];
}

- (void) setDisconnect {
    [BluetoothManager createManager].isConnected = NO;
    MBProgressHUD *shortHub = [[MBProgressHUD alloc]initWithView:[UIApplication sharedApplication].keyWindow];
    [[UIApplication sharedApplication].keyWindow addSubview:shortHub];
    [shortHub setLabelText:@"连接失败,请重试"];
    [shortHub setMode:MBProgressHUDModeText];
    [shortHub hide:YES afterDelay:1.5];
    [shortHub show:YES];
}
#pragma mark - 通过扫描到的设备刷新列表
-(void) peripheralFound:(CBPeripheral *)peripheral {

    [blueArray addObject:peripheral];
    [blueTableView reloadData];
}

@end
